/*
 * MySimpleValidate 0.1 - jQuery Plugin
 * Copyright (c) 2013 roast_soul
 * Email:roast_soul@126.com
 * Licensed under MIT and GPL
 * 2013-2-28 13:14:34
 */
(function($){
    $.fn.SetValidateRules = function(rules){
        $(this).each(function() {
            $(this).data("rules",rules);
            if(rules["required"]==true)
            {
                $(this).after("<span class='valid_required'>*</span>");
            }
            
            //add blur event 
            var blurevent=function(){
                $(this).DoValidate();
            };

            $(this).off("blur.ValidateRules");//under the ".ValidateRules" namespace
            $(this).on("blur.ValidateRules",blurevent);
        });
    };
    
    $.fn.SetAjaxValidate = function(param){
        $(this).each(function() {
            $(this).data("ajaxparam",param);
            //add blur event 
            var blurevent=function(){
                $(this).DoAjaxValidate(param);
            };
            $(this).off("blur.AjaxValidate");//under the ".AjaxValidate" namespace
            $(this).on("blur.AjaxValidate",blurevent);
        });
    };
    
    $.fn.DoValidate = function(){
        var allarevalid=true;//It may match multiple elements,so use each
        $(this).each(function() {
            var rules= $(this).data("rules");
            
            //            if($(this).next().is(".valid_msg"))
            //            {
            //                $(this).next().remove();
            //            }
            $(this).nextAll(".valid_msg").remove();
            if(rules["required"]==true&&$(this).val()=="")
            {
                $(this).after("<span class='valid_msg'>{0}</span>".replace("{0}",lang.mustinput));
                allarevalid=  false;
                addborderclass(false,$(this));
                return true;//continue;
            }
            
            if($(this).val()=="")//if the value is empty,no need to valid with below rules
            {
                clearorderclass($(this));
                return true;//continue;
            }
            
            if(rules["maxlength"]!=null&&$(this).val().length>rules["maxlength"])
            {
                var l=rules["maxlength"];
                $(this).after("<span class='valid_msg'>{0}</span>".replace("{0}",lang.maxlength.replace("{0}",l)));
                allarevalid=  false;
                addborderclass(false,$(this));
                return true;//continue;
            }
            
            if(rules["minlength"]!=null&&$(this).val().length<rules["minlength"])
            {
                var l=rules["minlength"];
                $(this).after("<span class='valid_msg'>{0}</span>".replace("{0}",lang.minlength.replace("{0}",l)));
                allarevalid=  false;
                addborderclass(false,$(this));
                return true;//continue;
            }
            
            if(rules["isemail"]==true)
            {
                var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
                if(reg.test($(this).val())==false)
                {
                    $(this).after("<span class='valid_msg'>{0}</span>".replace("{0}",lang.wrongemail));
                    allarevalid=  false;
                    addborderclass(false,$(this));
                    return true;//continue;
                }
            }
            
            if(rules["sameas"]!=null)
            {
                if($("#"+rules["sameas"]).val()!=$(this).val())
                {
                    $(this).after("<span class='valid_msg'>"+rules["sameas_msg"]+"</span>");
                    allarevalid=  false;
                    addborderclass(false,$(this));
                    return true;//continue;
                }
            }
            
            if(rules["expression"]!=null)
            {
                for(var i=0;i<rules["expression"].length;i++)
                {
                    var reg= rules["expression"][i]["exp"];
                    var msg= rules["expression"][i]["msg"];
                    if(reg.test($(this).val())==false)
                    {
                        $(this).after("<span class='valid_msg'>"+msg+"</span>");
                        allarevalid= false;
                        addborderclass(false,$(this));
                        return true;//continue;
                    }
                }  
            }
            addborderclass(true,$(this));
        });
        return allarevalid;
    };
    
    
    $.fn.DoAjaxValidate=function(){
        $(this).each(function() {
            $element=$(this);
            ajaxparam= $element.data("ajaxparam");
            url=""; 
            type="post";
            success_msg="";
            failed_msg="";
            img_ajaxloader_path="";
            if(ajaxparam["url"]!=null&&ajaxparam["url"]!="")
            {
                url=ajaxparam["url"];
            }
            if(ajaxparam["type"]!=null&&ajaxparam["type"]!="")
            {
                type=ajaxparam["type"];
            }
            if(ajaxparam["success_msg"]!=null&&ajaxparam["success_msg"]!="")
            {
                success_msg=ajaxparam["success_msg"];
            }
            if(ajaxparam["failed_msg"]!=null&&ajaxparam["failed_msg"]!="")
            {
                failed_msg=ajaxparam["failed_msg"];
            }
            if(ajaxparam["img_ajaxloader_path"]!=null&&ajaxparam["img_ajaxloader_path"]!="")
            {
                img_ajaxloader_path=ajaxparam["img_ajaxloader_path"];
            }
            
            data={};
            data[$element.attr("id")]=$element.val();
            var options = {
                type: type,
                url: url,
                data: data,
                dataType: "json"
            };
            $element.nextAll("img[name='imgajax']").remove();
            $element.after("<img name='imgajax' src='"+img_ajaxloader_path+"'>");
            $.ajax(options).done(
                function (result) {
                    if(result.value==true){
                        if(success_msg!=""){
                            $element.after("<span class='valid_msg'>"+success_msg+"</span>");
                        }
                    }
                    else
                    {
                        $element.nextAll(".valid_msg").remove();
                        $element.after("<span class='valid_msg'>"+failed_msg+"</span>");
                    }
                })
            .fail(function () {
                alert("Ajax validate error!");
            })
            .always(function(){
                $element.nextAll("img[name='imgajax']").remove();
            });
        });
        
    }
    addborderclass=function(bool,obj){
        if( bool==false)
        {
            $(obj).removeClass("valid_rightborder");
            $(obj).removeClass("valid_errorborder");
            $(obj).addClass("valid_errorborder");
        }
        else
        {
            $(obj).removeClass("valid_rightborder");
            $(obj).removeClass("valid_errorborder");
            $(obj).addClass("valid_rightborder");
        }
    };
    
    clearorderclass=function(obj)
    {
        $(obj).removeClass("valid_rightborder");
        $(obj).removeClass("valid_errorborder");
    };
})(jQuery);